package com.ctos.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctos.Exception.CustomException;
import com.ctos.common.BaseContext;
import com.ctos.entity.*;
import com.ctos.mapper.OrdersMapper;
import com.ctos.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {

    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private UserService userService;

    @Autowired
    private AddressBookService addressBookService;

    /**
     * 用户下单
     * @param orders
     */
    @Override
    @Transactional
    public void submit(Orders orders) {
        Long currentId = BaseContext.getCurrentId();

        //获取当前用户的购物车内的所有商品
        LambdaQueryWrapper<ShoppingCart> shoppingCartLambdaQueryWrapper = new LambdaQueryWrapper<>();
        shoppingCartLambdaQueryWrapper.eq(ShoppingCart::getUserId, currentId);
        List<ShoppingCart> shoppingCartList = shoppingCartService.list(shoppingCartLambdaQueryWrapper);

        if (shoppingCartList==null || shoppingCartList.size()==0){
            throw new CustomException("购物车内暂无商品");
        }

        //查询用户数据 和 收获地址数据
        User user = userService.getById(currentId);
        AddressBook userAddress = addressBookService.getById(orders.getAddressBookId());
        if (userAddress==null){
            throw new CustomException("地址为空,无法下单");
        }
    
        //生成订单号
        long ordersId = IdWorker.getId();

        //原子操作 保证多线程的情况下都不会出错
        AtomicInteger amount = new AtomicInteger(0);

        //收集订单详细数据
        List<OrderDetail> ordersDetails = shoppingCartList.stream().map((shoppingCart) -> {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(ordersId);
            orderDetail.setNumber(shoppingCart.getNumber());
            orderDetail.setDishFlavor(shoppingCart.getDishFlavor());
            orderDetail.setDishId(shoppingCart.getDishId());
            orderDetail.setSetmealId(shoppingCart.getSetmealId());
            orderDetail.setName(shoppingCart.getName());
            orderDetail.setImage(shoppingCart.getImage());
            orderDetail.setAmount(shoppingCart.getAmount());
            amount.addAndGet(shoppingCart.getAmount().multiply(new BigDecimal(shoppingCart.getNumber())).intValue());

            return orderDetail;
        }).collect(Collectors.toList());



        //向订单表插入数据
        orders.setUserId(currentId);
        orders.setConsignee(userAddress.getConsignee());
        orders.setAddress((userAddress.getProvinceName() == null ? "":userAddress.getProvinceName())
                +(userAddress.getDistrictName() == null ? "":userAddress.getDistrictName())
                +(userAddress.getDetail() == null ? "" : userAddress.getDetail()));
        orders.setNumber(String.valueOf(ordersId));
        orders.setId(ordersId);
        orders.setPhone(userAddress.getPhone());
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setStatus(2);
        orders.setUserName(user.getName());

        orders.setAmount(new BigDecimal(amount.get()));

        this.save(orders);
        //向订单明细表插入数据

        orderDetailService.saveBatch(ordersDetails);

        //清空购物车
        shoppingCartService.remove(shoppingCartLambdaQueryWrapper);

    }
}
